package com.ljl.question3;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.util.StringUtils;

/**
 * mqtt配置
 *
 * @author ljl
 */
@Configuration
public class MqttConfiguration {
    /**
     * 配置类
     *
     * @return /
     */
    @Bean
    @ConfigurationProperties(prefix = "mqtt")
    public MqttProperties mqttProperties() {
        return new MqttProperties();
    }

    /**
     * mqtt客户端配置
     *
     * @return /
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        // mqtt地址
        options.setServerURIs(new String[]{mqttProperties().getUrl()});
        // 账号
        String username = mqttProperties().getUsername();
        if (StringUtils.hasLength(username)) {
            options.setUserName(username);
        }
        // 密码
        String password = mqttProperties().getPassword();
        if (StringUtils.hasLength(password)) {
            options.setPassword(password.toCharArray());
        }
        factory.setConnectionOptions(options);
        return factory;
    }
}
